﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Text.RegularExpressions;

namespace IMark.DAO
{
    public class Utils
    {
        /// <param name="manager">Tham so "Admin" hoac "" se cho nguoi quan ly thuc hien.
        /// Neu Tham So SAdmin chi co Admin cao cap
        /// </param>
        public static bool CheckAuthentication(string manager = "Admin")
        {
            bool flag = false;
            NGUOI_DUNG nguoiDung = (NGUOI_DUNG)HttpContext.Current.Session["NGUOI_DUNG"];
            if (nguoiDung == null)
            {
                HttpContext.Current.Response.Redirect("~/Administrator");
            }
            else
            {
                if (nguoiDung.IDLoaiNguoiDung == 1 || nguoiDung.IDLoaiNguoiDung == 2)
                {
                    if (manager == "Admin")
                    {
                        return true;
                    }
                    else if (manager == "SAdmin" && nguoiDung.IDLoaiNguoiDung == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    HttpContext.Current.Response.Redirect("~/");
                }
            }
            return flag;
        }
        public static bool CheckSAdmin()
        {
            NGUOI_DUNG nguoiDung = (NGUOI_DUNG)HttpContext.Current.Session["NGUOI_DUNG"];
            if (nguoiDung == null)
            {
                return false;
            }
            else
            {
                if (nguoiDung.IDLoaiNguoiDung == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public static string ConvertMD5(string input)
        {
            MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            StringBuilder s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }
        public static void SendGMail(string mailto, string body, string title = "[EMart] Kích hoạt tài khoản")
        {
            CAU_HINH_WEBSITE cauHinh = CauHinhWebsiteModels.GetFirst();
            var fromAddress = cauHinh.SmtpGMail;
            var toAddress = mailto;
            string fromPassword = cauHinh.SmtpPassGMail;
            string subject = title;
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
            smtp.Send(fromAddress, toAddress, subject, body);
        }
        public static string ConvertUnSign(string text)
        {
            if (text != null)
            {
                for (int i = 32; i < 48; i++)
                {
                    if (i != 38 && i != 45)
                        text = text.Replace(((char)i).ToString(), " ");
                }
                text = text.Replace("-", "");
                text = text.Replace(".", "-");
                text = text.Replace(" ", "-");
                text = text.Replace(",", "-");
                text = text.Replace(";", "-");
                text = text.Replace(":", "-");
                text = text.Replace("|", "-");
                text = text.Replace("&", "_");
                text = text.Replace("?", "_");
                text = text.Replace("#", "_");
                text = text.Replace("%", "_");
                text = text.Replace("*", "_");
                text = text.Replace("<", "_");
                text = text.Replace(">", "_");
                text = text.Replace("--", "-");
                Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
                string strFormD = text.Normalize(NormalizationForm.FormD);
                return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
            }
            else
            {
                return null;
            }
        }
        public static string UploadImage(HttpPostedFile file, string destPath)
        {
            int nFileLen = file.ContentLength;
            if (nFileLen == 0)
            {
                return string.Empty;
            }
            string strExtLimited = ".bmp, .gif, .png, .jpg, .jpeg";
            string strExt = System.IO.Path.GetExtension(file.FileName).ToLower();

            if (strExtLimited.IndexOf(strExt) < 0)
            {
                return string.Empty;
            }
            int file_append = 0;
            string sFilename = System.IO.Path.GetFileName(file.FileName);
            string sSavePath;
            while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(destPath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(file.FileName) + file_append.ToString() + strExt;
            }
            sSavePath = HttpContext.Current.Server.MapPath(destPath + sFilename);
            file.SaveAs(sSavePath);
            return sFilename;
        }
        public static bool DeleteFile(string path)
        {
            try
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(path));
                return true;
            }
            catch (Exception)
            {
                return false;
                throw;
            }
        }
        public static void WriteCookie(string name, string value)
        {
            HttpCookie cokie = new HttpCookie(name, value);
            cokie.Expires = DateTime.Now.AddYears(2);
            HttpContext.Current.Response.Cookies.Add(cokie);
        }
        public static void DeleteCookie(string name)
        {
            HttpCookie cokie = new HttpCookie(name, "");
            cokie.Expires = DateTime.Now;
            HttpContext.Current.Response.Cookies.Add(cokie);
        }
        public static string ReadCookie(string name)
        {
            if (HttpContext.Current.Request.Cookies[name] != null)
            {
                return HttpContext.Current.Request.Cookies[name].Value;
            }
            else
            {
                return null;
            }
        }

        public static string GenerateRation(List<DANH_GIA> GG)
        {
            decimal tongsodanhgia = GG.Where(w => w.SoSao != 0).Count();
            decimal tongsosao = GG.Where(w => w.SoSao != 0).Sum(s => s.SoSao);
            decimal sao = 0;
            if (tongsodanhgia > 0 & tongsosao > 0)
                sao = Math.Round((tongsosao / tongsodanhgia));

            StringBuilder str = new StringBuilder();
            str.Append("<div class='rating'>");
            for (int i = 0; i < sao; i++)
            {
                str.Append("<i class='fa fa-star'></i>");
            }
            if (5 - sao > 0)
            {
                for (int i = 0; i < (5 - sao); i++)
                {
                    str.Append("<i class='fa fa-star-o'></i>");
                }
            }
            str.Append("</div>");
            return str.ToString();
        }
        public static bool DangKyMailNhanTin(DANG_KY_NHAN_MAIL dk)
        {
            try
            {
                using (EMartEntities db = new EMartEntities())
                {
                    var queryCheckMail = db.DANG_KY_NHAN_MAIL.Where(w => w.Email == dk.Email).ToList();
                    if (queryCheckMail.Count == 0)
                    {
                        db.DANG_KY_NHAN_MAIL.Add(dk);
                        db.SaveChanges();
                    }
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}